package com.study.favorite.biz;

import com.study.favorite.mapper.FavoriteMapper;
import com.study.favorite.mapper.TagFavoriteMapper;
import com.study.favorite.mapper.TagMapper;
import com.study.favorite.pojo.Favorite;
import com.study.favorite.pojo.Tag;
import com.study.favorite.util.MybatisHelper;
import lombok.val;
import org.apache.ibatis.session.SqlSession;

public class FavBizImpl implements FavBiz{
    @Override
    public void addFav(Favorite favorite) {
        SqlSession sqlSession = MybatisHelper.openSession();
        try{
            FavoriteMapper favoriteMapper = sqlSession.getMapper(FavoriteMapper.class);
            TagMapper tagMapper = sqlSession.getMapper(TagMapper.class);
            TagFavoriteMapper tagFavoriteMapper= sqlSession.getMapper(TagFavoriteMapper.class);
            // 省略字段验证
            // 保存链接
            favoriteMapper.insert(favorite);
            // 分析 ftags 字段 ： 门户，新闻。体育
            String[] tags = favorite.getFtags().split("[,，;：；\\-\\s]+");

            for (String tag : tags) {
                if(tagMapper.updateCount(tag) == 0){
                    Tag t = new Tag();
                    t.setTname(tag);
                    t.setTcount(1);
                    // 新增分类
                    tagMapper.insert(t);
                    // 新增中间表记录
                    tagFavoriteMapper.insert(t.getTid(), favorite.getFid());
                }else {
                    // 新增中间表记录
                    tagFavoriteMapper.insertByTname(tag, favorite.getFid());
                }
            }
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
        }finally {
            sqlSession.close();
        }
    }
}
